package com.game.game.service.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.game.core.db.service.proxy.EntityProxyFactory;
import com.game.core.net.common.RemoteNode;
import com.game.core.service.PublicService;
import com.game.core.service.ServiceContainer;
import com.game.dbpersistence.game.entity.AccountEntity;
import com.game.dbpersistence.game.entity.BuncherEntity;
import com.game.dbpersistence.game.entity.FashionEntity;
import com.game.dbpersistence.game.entity.ItemEntity;
import com.game.dbpersistence.game.entity.WeaponEntity;
import com.game.dbpersistence.game.entity.WeaponsetEntity;
import com.game.game.GameServer;
import com.game.game.config.FashionConfig;
import com.game.game.config.PlayerConfig;
import com.game.game.config.WeaponConfig;
import com.game.game.config.WeaponStrengthenConfig;
import com.game.game.config.XMLTemplateService;
import com.game.game.service.item.ItemService;
import com.game.game.util.FileReaderUtil;
import com.game.message.proto.player.PlayerProtoBuf.GWChangePlayerInfoRES;
import com.game.message.proto.player.PlayerProtoBuf.WGChangePlayerInfoREQ;
import com.game.message.proto.weapon.WeaponProtoBuf.FashionInfo;
import com.game.message.protocol.ProtocolsConfig;

public class PlayerService extends PublicService {
	final static Logger logger = LoggerFactory.getLogger(PlayerService.class);
	
	//public static List<String> allNameList = new ArrayList<>();
	public static List<String> badWordList = new ArrayList<>();
	
	@Override
	public int init() {
		this.initBadWordList();
		//this.initAllNameList();
		return 0;
	}
	
//	public void initAllNameList() {
//		List<AccountEntity> accountEntityList = GameServer.accountEntityService.getAccountList();
//		for (AccountEntity accountEntity : accountEntityList) {
//			allNameList.add(accountEntity.getName());
//		}
//	}
	public void initBadWordList() {
		String badWordsPath =System.getProperty("user.dir")+ "/config/badword.txt";
		String badWords = FileReaderUtil.getFileString(badWordsPath);
		String[] badWordsArr = badWords.split(";");
		for (String badWord : badWordsArr) {
			badWordList.add(badWord);
		}
	}
	
	public GWChangePlayerInfoRES changePlayerInfo (RemoteNode remoteNode, WGChangePlayerInfoREQ message, int callback) {
		String account = message.getAccount();
		String newName = message.getName();
		String newAppearance = message.getAppearance();
		FashionInfo fashionInfo = message.getFashionInfo();
		int newSex = message.getSex();
		GWChangePlayerInfoRES.Builder sendBuilder = GWChangePlayerInfoRES.newBuilder();
		sendBuilder.setAccount(account);

		int result = this.checkNameValid(newName);
		if (result == ProtocolsConfig.CHANGE_PLAYER_INFO_SUCCESS) {
			result = this.updatePlayerInfoEntity(account, newName, newAppearance, newSex, fashionInfo);
		}
		if (result == ProtocolsConfig.CHANGE_PLAYER_INFO_SUCCESS) {
			AccountEntity accountEntity = GameServer.accountEntityService.getAccount(account);
			if(accountEntity != null) {
				sendBuilder.setExperience(accountEntity.getExperience());
				sendBuilder.setGoldCoin(accountEntity.getGoldCoin());
				sendBuilder.setDiamonds(accountEntity.getDiamonds());
				sendBuilder.setGiftCert(accountEntity.getGiftCert());
				sendBuilder.setFeats(accountEntity.getFeats());
			}
			List<BuncherEntity> buncherList = GameServer.buncherEntityService.getBuncherList(account);
			if ((buncherList != null) && (buncherList.size() > 0)) {
				for (BuncherEntity entity : buncherList) {
					sendBuilder.addBuncherInfos(entity.toProto());
				}
			}
			List<FashionEntity> fashionList = GameServer.fashionEntityService.getFashionList(account);
			if ((fashionList != null) && (fashionList.size() > 0)) {
				for (FashionEntity entity : fashionList) {
					sendBuilder.addFashionInfos(entity.toProto());
				}
			}
			List<ItemEntity> itemList = GameServer.itemEntityService.getItemList(account);
			if ((itemList != null) && (itemList.size() > 0)) {
				for (ItemEntity entity : itemList) {
					sendBuilder.addItemInfos(entity.toProto());
				}
			}
			List<WeaponEntity> weaponList = GameServer.weaponEntityService.getWeaponList(account);
			if ((weaponList != null) && (weaponList.size() > 0)) {
				for (WeaponEntity entity : weaponList) {
					sendBuilder.addWeaponInfos(entity.toProto());
				}
			}
			List<WeaponsetEntity> weaponsetList = GameServer.weaponsetEntityService.getWeaponsetList(account);
			if ((weaponsetList != null) && (weaponsetList.size() > 0)) {
				for (WeaponsetEntity entity : weaponsetList) {
					sendBuilder.addWeaponSetInfos(entity.toProto());
				}
			}
		}
		sendBuilder.setCurrentWeaponSet(1);
		sendBuilder.setResult(result);
		return sendBuilder.build();
	}
	
	public int checkNameValid(String name) {
		//bad words
//		for (String badWord : badWordList) {
//			if (!"".equals(badWord) && name.contains(badWord)) return ProtocolsConfig.INVALID_NAME_CHAR;
//		}
//		//valid
//		int checkNameResult = CharUtil.checkNameValid(name);
//		if (checkNameResult != ProtocolsConfig.CHANGE_PLAYER_INFO_SUCCESS) return checkNameResult;
//		//exist
//		if (allNameList.contains(name)) return ProtocolsConfig.NAME_TAKEN;
		return ProtocolsConfig.CHANGE_PLAYER_INFO_SUCCESS;
	}
	
	public int updatePlayerInfoEntity(String account, String newName, String newAppearance, int newSex, FashionInfo fashionInfo) {
		try {
			AccountEntity accountEntity = GameServer.accountEntityService.getAccount(account);
			if(accountEntity != null) {
				EntityProxyFactory entityProxyFactory = new EntityProxyFactory();
				AccountEntity proxyAccountEntity = entityProxyFactory.createProxyEntity(accountEntity);
				//更新allNameList
				//allNameList.remove(accountEntity.getName() == null ? "" : accountEntity.getName());
				//allNameList.add(newName);
				if (newName != null && newName.length() >0) proxyAccountEntity.setName(newName);
				if (newAppearance != null && newAppearance.length() > 0) proxyAccountEntity.setAppearance(newAppearance);
				if (newSex != 0) proxyAccountEntity.setSex(newSex);
				
				if((accountEntity.getSex() == 0)&&(newSex != 0)) {
					this.registPlayer(proxyAccountEntity);
				}else {
					GameServer.accountEntityService.updateAccount(proxyAccountEntity);
				}
			}
			
			FashionEntity fashionEntity = GameServer.fashionEntityService.getFashion(account, fashionInfo.getFashionId());
			if (fashionEntity != null) {
				fashionEntity.setSkinColour(fashionInfo.getSkinColour());
				fashionEntity.setHairColour(fashionInfo.getHairColour());
				fashionEntity.setMainbodyColour(fashionInfo.getMainbodyColour());
				fashionEntity.setDecorateColour(fashionInfo.getDecorateColour());
				String skinColours = JSON.toJSONString(fashionInfo.getSkinColoursList());
				fashionEntity.setSkinColours(skinColours);
				String hairColours = JSON.toJSONString(fashionInfo.getHairColoursList());
				fashionEntity.setHairColours(hairColours);
				String mainbodyColours = JSON.toJSONString(fashionInfo.getMainbodyColoursList());
				fashionEntity.setMainbodyColours(mainbodyColours);
				String decorateColours = JSON.toJSONString(fashionInfo.getDecorateColoursList());
				fashionEntity.setDecorateColours(decorateColours);
				GameServer.fashionEntityService.updateFashion(fashionEntity);
			} else {
				fashionEntity = new FashionEntity();
				fashionEntity.setOwnerId(account);
				fashionEntity.setFashionId(fashionInfo.getFashionId());
				fashionEntity.setSkinColour(fashionInfo.getSkinColour());
				fashionEntity.setHairColour(fashionInfo.getHairColour());
				fashionEntity.setMainbodyColour(fashionInfo.getMainbodyColour());
				fashionEntity.setDecorateColour(fashionInfo.getDecorateColour());
				String skinColours = JSON.toJSONString(fashionInfo.getSkinColoursList());
				fashionEntity.setSkinColours(skinColours);
				String hairColours = JSON.toJSONString(fashionInfo.getHairColoursList());
				fashionEntity.setHairColours(hairColours);
				String mainbodyColours = JSON.toJSONString(fashionInfo.getMainbodyColoursList());
				fashionEntity.setMainbodyColours(mainbodyColours);
				String decorateColours = JSON.toJSONString(fashionInfo.getDecorateColoursList());
				fashionEntity.setDecorateColours(decorateColours);
				GameServer.fashionEntityService.insertFashion(fashionEntity);
			}

			List<WeaponsetEntity> weaponSetEntityList = GameServer.weaponsetEntityService.getWeaponsetList(account);
			for (WeaponsetEntity weaponSetEntity : weaponSetEntityList) {
				EntityProxyFactory weaponEntityProxy = new EntityProxyFactory();
				WeaponsetEntity proxyWeaponsetEntity = weaponEntityProxy.createProxyEntity(weaponSetEntity);
				proxyWeaponsetEntity.setFashionId(fashionEntity.getFashionId());
				GameServer.weaponsetEntityService.updateWeaponset(proxyWeaponsetEntity);
			}

			return ProtocolsConfig.CHANGE_PLAYER_INFO_SUCCESS;
		}catch (Exception e) {
			logger.error(e.toString());
			return ProtocolsConfig.INVALID_PLAYER_INFO_PARAMS;
		}
	}
	
	public void registPlayer(AccountEntity accountEntity) throws Exception {
		PlayerConfig playerConfig = XMLTemplateService.playerConfigMap.get(accountEntity.getSex());
		if(playerConfig==null) {
			return;
		}
		int defaultEquipWeaponId = playerConfig.getWeaponId();
		int defaultEquipFashionId = playerConfig.getFashionId();
		int experience = playerConfig.getExperience();
		int goldCoin = playerConfig.getGoldCoin();
		int diamonds = playerConfig.getDiamonds();
		int giftCert = playerConfig.getGiftCert();
		int feats = playerConfig.getFeats();
		accountEntity.setExperience(experience);
		accountEntity.setGoldCoin(goldCoin);
		accountEntity.setDiamonds(diamonds);
		accountEntity.setGiftCert(giftCert);
		accountEntity.setFeats(feats);

		GameServer.accountEntityService.updateAccount(accountEntity);
		//////////////////////////////////////////////////////////////////////////////////////////
		if (GameServer.fashionEntityService == null) {
			GameServer.fashionEntityService = GameServer.getFashionEntityProxyService(GameServer.classPathXmlApplicationContext);
		}
		List<FashionEntity> fashionList = GameServer.fashionEntityService.getFashionList(accountEntity.getAcc());
		if(fashionList.size() <= 0) {
			for(Integer fashionId : playerConfig.getFashions()){
				FashionConfig fashionConfig = XMLTemplateService.fashionConfigMap.get(fashionId);
				if(fashionConfig != null) {
					FashionEntity fashionEntity = new FashionEntity();
					fashionEntity.setOwnerId(accountEntity.getAcc());
					fashionEntity.setFashionId(fashionConfig.getFashionId());
					fashionEntity.setUnlocked(fashionConfig.getStatus());
					fashionEntity.setHairColour(1);
					fashionEntity.setSkinColour(1);
					fashionEntity.setMainbodyColour(1);
					fashionEntity.setDecorateColour(1);
					fashionEntity.setSkinColours("[1]");
					fashionEntity.setHairColours("[1]");
					fashionEntity.setMainbodyColours("[1]");
					fashionEntity.setDecorateColours("[1]");
					fashionList.add(fashionEntity);
				}
			}
			if(fashionList.size() > 0) {
				List<Long> rets = GameServer.fashionEntityService.insertFashionList(fashionList);
				if(rets!=null){
					int index = 0;
					for (Long ret :rets ) {
						if(ret == 0) {
							logger.error("GameServer.registPlayer.insertWeapon() Filed ! fashionEntity={}", fashionList.get(index).toString());
						}
						index++;
					}
				}
			}
		}
		
		//////////////////////////////////////////////////////////////////////////////////////////
		//init weapon
		if (GameServer.weaponEntityService == null) {
			GameServer.weaponEntityService = GameServer.getWeaponEntityProxyService(GameServer.classPathXmlApplicationContext);
		}
		String defaultEquipWeaponUid = "";	
		List<WeaponEntity> weaponList = GameServer.weaponEntityService.getWeaponList(accountEntity.getAcc());
		if(weaponList.size() <= 0) {
			for (Integer weaponId : playerConfig.getWeapons()) {
				WeaponConfig weaponConfig = XMLTemplateService.weaponConfigMap.get(weaponId);
				if (weaponConfig != null) {
					String name = weaponConfig.getName();
					int weaponType = weaponConfig.getWeaponType();
					int weaponLevel = weaponConfig.getWeaponLevel();
					// int weaponMaxLevel = weaponConfig.getWeaponMaxLevel();
					int mainSkillId = weaponConfig.getMainSkillId();
	
					WeaponEntity weaponEntity = new WeaponEntity();
					weaponEntity.setOwnerId(accountEntity.getAcc());
					weaponEntity.setWeaponId(weaponId);
					weaponEntity.setName(name);
					weaponEntity.setWeaponType(weaponType);
					weaponEntity.setWeaponLevel(weaponLevel);
					// weaponEntity.setWeaponMaxLevel(weaponMaxLevel);
					weaponEntity.setMainSkillId(mainSkillId);
					WeaponStrengthenConfig weaponStrengthenConfig = XMLTemplateService.weaponStrengthenConfigMap.get(weaponId);
					if ((weaponStrengthenConfig != null) && (weaponStrengthenConfig.getMainNodeList().size() > 0)) {
						weaponEntity.setMainNodeList(weaponStrengthenConfig.getMainNodeList());
					}
					weaponList.add(weaponEntity);
					if(weaponId == defaultEquipWeaponId) {
						defaultEquipWeaponUid = weaponEntity.getUid();
					}
				}
			}
			if (weaponList.size() > 0) {
				List<Long> rets = GameServer.weaponEntityService.insertWeaponList(weaponList);
				if (rets != null) {
					int index = 0;
					for (Long ret : rets) {
						if (ret == 0) {
							logger.error("GameServer.registPlayer.insertWeapon() Filed ! weaponEntity={}",
									weaponList.get(index).toString());
						}
						index++;
					}
				}
			}
		}
		//////////////////////////////////////////////////////////////////////////////////////////
		//init weapon_set
		if (GameServer.weaponsetEntityService == null) {
			GameServer.weaponsetEntityService = GameServer.getWeaponsetEntityProxyService(GameServer.classPathXmlApplicationContext);
		}
		List<WeaponsetEntity> weaponsetList = GameServer.weaponsetEntityService.getWeaponsetList(accountEntity.getAcc());
		if(weaponsetList.size() <= 0) {
			for (int i = 1; i <= 5; i++) {
				WeaponsetEntity weaponsetEntity = new WeaponsetEntity();
				weaponsetEntity.setOwnerId(accountEntity.getAcc());
				weaponsetEntity.setSetId(i);
				if((i == 1)&&(!defaultEquipWeaponUid.isEmpty())) {
					weaponsetEntity.setWeapon1(defaultEquipWeaponUid);
				}else {
					weaponsetEntity.setWeapon1("0");
				}
				weaponsetEntity.setWeapon2("0");
				weaponsetEntity.setWeapon3("0");
				weaponsetEntity.setWeapon4("0");
				weaponsetEntity.setFashionId(defaultEquipFashionId);
				weaponsetList.add(weaponsetEntity);
			}
			if(weaponsetList.size() > 0) {
				List<Long> rets = GameServer.weaponsetEntityService.insertWeaponsetList(weaponsetList);
				if(rets!=null){
					int index = 0;
					for (Long ret :rets ) {
						if(ret == 0) {
							logger.error("GameServer.registPlayer.insertWeaponset() Filed ! weaponsetEntity={}", weaponList.get(index).toString());
						}
						index++;
					}
				}
			}
//			if(!defaultEquipWeaponUid.isEmpty()) {
//				WeaponService weaponService = ServiceContainer.getInstance().getPublicService(WeaponService.class);
//				weaponService.ChangeEquipWeaponEntity(accountEntity.getAcc(), defaultEquipWeaponUid, 1, 1);
//			}
		}

		//测试用，根据配表发道具
		HashMap<Integer, Integer> itemMap = new HashMap<>();
		for (String item : playerConfig.getItems()) {
			String itemId = item.split(",")[0];
			String itemNu = item.split(",")[1];
			itemMap.put(Integer.parseInt(itemId),Integer.parseInt(itemNu));
		}
		ItemService itemService = ServiceContainer.getInstance().getPublicService(ItemService.class);
		itemService.addItem(accountEntity.getAcc(), itemMap ,1);
	}
}
